<template>
  <div class="brand-carousel-container">
    <div class="brand-carousel-title" v-if="title">
      <span>{{ title }}</span>
    </div>
    <div class="brand-carousel-wrapper" ref="carouselRef">
      <div
        class="brand-carousel-track"
        :style="{
          transform: `translateX(-${translateX}px)`,
          transition: isTransitioning ? 'transform 0.5s cubic-bezier(0.25, 0.1, 0.25, 1)' : 'none'
        }"
      >
        <div
          v-for="(brand, index) in displayBrands"
          :key="index"
          class="brand-item"
          @click="handleBrandClick(brand.original, brand.originalIndex)"
        >
          <div class="brand-image-wrapper">
            <img
              :src="brand.original.image"
              :alt="brand.original.name || `品牌 ${brand.originalIndex + 1}`"
              class="brand-image"
              @load="handleImageLoad"
              @error="handleImageError"
            />
          </div>
          <div class="brand-name" v-if="showBrandName && brand.original.name">{{ brand.original.name }}</div>
        </div>
      </div>

      <!-- 左右箭头 -->
      <button
        v-if="showArrows && displayBrands.length > visibleItems"
        class="brand-arrow brand-arrow-left"
        @click="prevSlide"
        :disabled="!infinite && currentIndex === 0"
      >
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
          <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </button>

      <button
        v-if="showArrows && displayBrands.length > visibleItems"
        class="brand-arrow brand-arrow-right"
        @click="nextSlide"
        :disabled="!infinite && currentIndex >= displayBrands.length - visibleItems"
      >
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
          <path d="M9 18L15 12L9 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </button>
    </div>

    <!-- 指示器 -->
    <div v-if="showIndicators && displayBrands.length > visibleItems" class="brand-indicators">
      <button
        v-for="i in indicatorCount"
        :key="i-1"
        class="brand-indicator"
        :class="{ active: currentIndex >= (i-1) * indicatorStep && currentIndex < i * indicatorStep }"
        @click="goToSlide((i-1) * indicatorStep)"
      ></button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'

// Props定义
const props = defineProps({
  // 品牌数组
  brands: {
    type: Array,
    required: true,
    default: () => []
  },
  // 标题
  title: {
    type: String,
    default: '官方合作伙伴'
  },
  // 是否显示品牌名称
  showBrandName: {
    type: Boolean,
    default: false
  },
  // 自动播放
  autoPlay: {
    type: Boolean,
    default: true
  },
  // 自动播放间隔（毫秒）
  interval: {
    type: Number,
    default: 3000
  },
  // 是否显示箭头
  showArrows: {
    type: Boolean,
    default: false
  },
  // 是否显示指示器
  showIndicators: {
    type: Boolean,
    default: false
  },
  // 是否无限循环
  infinite: {
    type: Boolean,
    default: true
  },
  // 可见项目数量
  visibleItems: {
    type: Number,
    default: 6
  },
  // 每次滚动的项目数量
  scrollItems: {
    type: Number,
    default: 1
  },
  // 初始索引
  initialIndex: {
    type: Number,
    default: 0
  }
})

// Emits定义
const emit = defineEmits(['change', 'click'])

// 响应式数据
const currentIndex = ref(props.initialIndex)
const isTransitioning = ref(true)
const autoPlayTimer = ref(null)
const isAutoPlayPaused = ref(false)
const carouselRef = ref(null)
const itemWidth = ref(0)
const translateX = ref(0)

// 触摸相关
const touchState = reactive({
  startX: 0,
  startY: 0,
  deltaX: 0,
  deltaY: 0,
  isSwiping: false
})

// 计算属性
const totalItems = computed(() => props.brands.length)

// 计算指示器数量
const indicatorStep = computed(() => props.scrollItems)
const indicatorCount = computed(() => {
  return Math.ceil((totalItems.value - props.visibleItems + 1) / indicatorStep.value)
})

// 创建用于显示的品牌数组，确保无限循环时始终显示指定数量的图片
const displayBrands = computed(() => {
  if (props.brands.length === 0) return []

  // 如果品牌数量不足visibleItems，则复制品牌以填充
  let result = []
  let brandsToUse = [...props.brands]

  // 确保品牌数量至少是可见数量的3倍，以实现无缝循环
  if (props.infinite) {
    // 计算需要复制的次数，确保至少有visibleItems * 3个品牌
    const requiredCopies = Math.ceil((props.visibleItems * 3) / props.brands.length)

    // 创建足够多的品牌副本
    brandsToUse = []
    for (let i = 0; i < requiredCopies; i++) {
      brandsToUse = [...brandsToUse, ...props.brands]
    }
  }

  // 为每个品牌添加原始索引信息
  result = brandsToUse.map((brand, index) => ({
    original: brand,
    originalIndex: index % props.brands.length
  }))

  return result
})

// 更新translateX
const updateTranslateX = () => {
  translateX.value = currentIndex.value * itemWidth.value
}

// 方法
const nextSlide = () => {
  // 如果没有足够的品牌或者displayBrands为空，则不执行滚动
  if (displayBrands.value.length <= props.visibleItems) return

  const maxIndex = displayBrands.value.length - props.visibleItems

  // 在无限循环模式下处理边界情况
  if (props.infinite && currentIndex.value >= maxIndex - props.visibleItems) {
    // 如果接近末尾，先正常滚动
    isTransitioning.value = true
    currentIndex.value = currentIndex.value + props.scrollItems
    updateTranslateX()

    // 然后在过渡完成后，禁用过渡效果并跳回到前面的等效位置
    setTimeout(() => {
      isTransitioning.value = false
      currentIndex.value = props.brands.length
      updateTranslateX()

      // 确保DOM更新后再启用过渡效果
      nextTick(() => {
        setTimeout(() => {
          isTransitioning.value = true
        }, 50)
      })
    }, 500) // 等待过渡完成
  } else {
    // 正常滚动
    isTransitioning.value = true
    if (props.infinite) {
      currentIndex.value = currentIndex.value + props.scrollItems
    } else {
      currentIndex.value = Math.min(currentIndex.value + props.scrollItems, maxIndex)
    }
    updateTranslateX()
  }
}

const prevSlide = () => {
  // 如果没有足够的品牌或者displayBrands为空，则不执行滚动
  if (displayBrands.value.length <= props.visibleItems) return

  const maxIndex = displayBrands.value.length - props.visibleItems

  // 在无限循环模式下处理边界情况
  if (props.infinite && currentIndex.value <= props.brands.length) {
    // 如果接近开头，先正常滚动
    isTransitioning.value = true
    currentIndex.value = currentIndex.value - props.scrollItems
    updateTranslateX()

    // 如果滚动到了最前面，在过渡完成后，禁用过渡效果并跳到后面的等效位置
    if (currentIndex.value < props.scrollItems) {
      setTimeout(() => {
        isTransitioning.value = false
        currentIndex.value = maxIndex - props.visibleItems
        updateTranslateX()

        // 确保DOM更新后再启用过渡效果
        nextTick(() => {
          setTimeout(() => {
            isTransitioning.value = true
          }, 50)
        })
      }, 500) // 等待过渡完成
    }
  } else {
    // 正常滚动
    isTransitioning.value = true
    if (props.infinite) {
      currentIndex.value = Math.max(currentIndex.value - props.scrollItems, 0)
    } else {
      currentIndex.value = Math.max(currentIndex.value - props.scrollItems, 0)
    }
    updateTranslateX()
  }
}

const goToSlide = (index) => {
  if (index >= 0 && index <= displayBrands.value.length - props.visibleItems) {
    // 启用过渡效果
    isTransitioning.value = true
    currentIndex.value = index
    updateTranslateX()
  }
}

// 自动播放控制
const startAutoPlay = () => {
  if (!props.autoPlay || displayBrands.value.length <= props.visibleItems) return

  stopAutoPlay()
  autoPlayTimer.value = setInterval(() => {
    if (!isAutoPlayPaused.value) {
      nextSlide()
    }
  }, props.interval)
}

const stopAutoPlay = () => {
  if (autoPlayTimer.value) {
    clearInterval(autoPlayTimer.value)
    autoPlayTimer.value = null
  }
}

const pauseAutoPlay = () => {
  isAutoPlayPaused.value = true
}

const resumeAutoPlay = () => {
  isAutoPlayPaused.value = false
}

// 触摸事件处理
const handleTouchStart = (e) => {
  const touch = e.touches[0]
  touchState.startX = touch.clientX
  touchState.startY = touch.clientY
  touchState.isSwiping = false
  pauseAutoPlay()
}

const handleTouchMove = (e) => {
  if (!touchState.startX) return

  const touch = e.touches[0]
  touchState.deltaX = touch.clientX - touchState.startX
  touchState.deltaY = touch.clientY - touchState.startY

  // 判断是否为水平滑动
  if (Math.abs(touchState.deltaX) > Math.abs(touchState.deltaY)) {
    touchState.isSwiping = true
    e.preventDefault()
  }
}

const handleTouchEnd = () => {
  if (!touchState.isSwiping) {
    resumeAutoPlay()
    return
  }

  const threshold = 50 // 滑动阈值

  if (Math.abs(touchState.deltaX) > threshold) {
    if (touchState.deltaX > 0) {
      prevSlide()
    } else {
      nextSlide()
    }
  }

  // 重置触摸状态
  touchState.startX = 0
  touchState.startY = 0
  touchState.deltaX = 0
  touchState.deltaY = 0
  touchState.isSwiping = false

  resumeAutoPlay()
}

// 图片加载处理
const handleImageLoad = (e) => {
  // 确保图片平滑显示
  e.target.style.opacity = '1';
}

const handleImageError = (e) => {
  console.error('图片加载失败:', e.target.src)
  // 设置默认图片
  e.target.src = 'https://via.placeholder.com/200x100?text=品牌图片';
  e.target.style.opacity = '1';
}

// 品牌点击事件
const handleBrandClick = (brand, index) => {
  emit('click', { brand, index })
}

// 计算每个品牌项的宽度
const calculateItemWidth = () => {
  if (!carouselRef.value) return

  const containerWidth = carouselRef.value.clientWidth - 80 // 减去左右padding (40px * 2)
  itemWidth.value = containerWidth / props.visibleItems

  // 设置每个品牌项的宽度
  const brandItems = carouselRef.value.querySelectorAll('.brand-item')
  brandItems.forEach(item => {
    item.style.width = `${itemWidth.value}px`
  })

  updateTranslateX()
}

// 监听器
watch(currentIndex, (newIndex, oldIndex) => {
  emit('change', {
    currentIndex: newIndex,
    previousIndex: oldIndex,
    currentBrand: props.brands[newIndex]
  })
})

watch(() => props.autoPlay, (newVal) => {
  if (newVal) {
    startAutoPlay()
  } else {
    stopAutoPlay()
  }
})

watch(() => props.interval, () => {
  if (props.autoPlay) {
    startAutoPlay()
  }
})

watch(() => props.visibleItems, () => {
  nextTick(() => {
    calculateItemWidth()
  })
})

// 监听窗口大小变化，重新计算品牌项目宽度
watch(() => displayBrands.value, () => {
  nextTick(() => {
    calculateItemWidth()
  })
})

// 生命周期
onMounted(() => {
  // 如果启用无限循环，设置初始索引为一个合适的值，确保有足够的空间向前滚动
  // 并且确保初始状态下显示完整的品牌数量
  if (props.infinite) {
    // 设置初始位置为品牌数组的第一个完整循环的开始位置
    currentIndex.value = props.brands.length
  }

  nextTick(() => {
    calculateItemWidth()

    // 确保初始状态下不显示过渡效果
    isTransitioning.value = false
    updateTranslateX()

    // 短暂延迟后启用过渡效果，以避免初始加载时的闪动
    setTimeout(() => {
      isTransitioning.value = true
    }, 50)

    if (props.autoPlay) {
      // 延迟启动自动播放，确保初始渲染完成
      setTimeout(() => {
        startAutoPlay()
      }, 500)
    }
  })

  // 添加事件监听
  window.addEventListener('resize', calculateItemWidth)
  carouselRef.value.addEventListener('touchstart', handleTouchStart, { passive: false })
  carouselRef.value.addEventListener('touchmove', handleTouchMove, { passive: false })
  carouselRef.value.addEventListener('touchend', handleTouchEnd)
  carouselRef.value.addEventListener('mouseenter', pauseAutoPlay)
  carouselRef.value.addEventListener('mouseleave', resumeAutoPlay)
})

onUnmounted(() => {
  stopAutoPlay()
  window.removeEventListener('resize', calculateItemWidth)
  if (carouselRef.value) {
    carouselRef.value.removeEventListener('touchstart', handleTouchStart)
    carouselRef.value.removeEventListener('touchmove', handleTouchMove)
    carouselRef.value.removeEventListener('touchend', handleTouchEnd)
    carouselRef.value.removeEventListener('mouseenter', pauseAutoPlay)
    carouselRef.value.removeEventListener('mouseleave', resumeAutoPlay)
  }
})

// 暴露方法给父组件
defineExpose({
  nextSlide,
  prevSlide,
  goToSlide,
  startAutoPlay,
  stopAutoPlay,
  pauseAutoPlay,
  resumeAutoPlay,
  currentIndex: computed(() => currentIndex.value)
})
</script>

<style scoped>
.brand-carousel-container {
  width: 100%;
  margin: 0 auto;
  padding: 20px 0;
  position: relative;
  border-radius: 8px;
}

.brand-carousel-title {
  text-align: center;
  margin-bottom: 40px;
  position: relative;
}

.brand-carousel-title span {
  font-size: 22px;
  font-weight: 500;
  color: #787878;
  position: relative;
  padding: 0 50px;
}

.brand-carousel-title span::before,
.brand-carousel-title span::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 30px;
  height: 1px;
  background-color: #ccc;
}

.brand-carousel-title span::before {
  left: -20px;
}

.brand-carousel-title span::after {
  right: -20px;
}

.brand-carousel-wrapper {
  position: relative;
  width: 100%;
  overflow: hidden;
  padding: 0 40px;
  box-sizing: border-box;
  /* 确保容器宽度固定 */
  display: flex;
  flex-direction: column;
}

.brand-carousel-track {
  display: flex;
  will-change: transform;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  transform-style: preserve-3d;
  perspective: 1000;
  -webkit-perspective: 1000;
  /* 确保轨道宽度足够容纳所有品牌项目 */
  width: max-content;
  /* 确保品牌项目均匀分布 */
  justify-content: space-between;
}

.brand-item {
  flex: 0 0 auto;
  padding: 10px 0;
  box-sizing: border-box;
  text-align: center;
  cursor: pointer;
  transition: transform 0.3s ease;
  /* 确保每个品牌项占据固定宽度 */
  width: 20%; /* 默认值，会被JS动态覆盖 */
  display: flex;
  justify-content: center;
  /* 防止闪动 */
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
}

.brand-item:hover {
  transform: translateY(-5px) translateZ(0);
  -webkit-transform: translateY(-5px) translateZ(0);
}

.brand-image-wrapper {
  margin-bottom: 8px;
  height: 160px;
  width: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
  /* 防止闪动 */
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
}

.brand-image {
  border-radius: 20px;
  width: 100%;
  height: 100%;
  object-fit: cover;
  /* 防止图片闪动 */
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
  /* 确保图片平滑加载 */
  opacity: 1;
  transition: opacity 0.3s ease;
}

.brand-name {
  font-size: 14px;
  color: #666;
  margin-top: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 箭头样式 */
.brand-arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.8);
  color: #333;
  border: 1px solid #eee;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  z-index: 2;
}

.brand-arrow:hover {
  background: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.brand-arrow:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.brand-arrow-left {
  left: 5px;
}

.brand-arrow-right {
  right: 5px;
}

/* 指示器样式 */
.brand-indicators {
  display: flex;
  justify-content: center;
  margin-top: 15px;
  gap: 8px;
}

.brand-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #ddd;
  border: none;
  padding: 0;
  cursor: pointer;
  transition: all 0.3s ease;
}

.brand-indicator.active {
  background-color: #666;
  transform: scale(1.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .brand-carousel-wrapper {
    padding: 0 30px;
  }

  .brand-arrow {
    width: 30px;
    height: 30px;
  }

  .brand-image-wrapper {
    height: 60px;
    padding: 10px;
  }

  .brand-name {
    font-size: 12px;
  }
}
</style>
